﻿
using Product.Domain.Services;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace Product.Infrastructure
{
    public static class ServiceExtension
    {
        public static void AddProductServices(this IServiceCollection services)
        {
            //注册所有Repository
            foreach (var item in AddRepository("I", "Repository"))
            {
                services.AddScoped(item.Value, item.Key);
            }
          
            services.AddScoped<ProductService>();
       
        }

        /// <summary>
        /// 获取程序集中的实现类与对应接口
        /// </summary>
        /// <param name="prefix">Prefix.接口头部</param>
        /// <param name="endwith">类名结尾</param>
        private static Dictionary<Type, Type> AddRepository(string prefix, string endwith)
        {
            var result = new Dictionary<Type, Type>();
            foreach (var item in Assembly.GetExecutingAssembly().GetTypes().Where(c => !c.IsInterface && c.Name.ToUpper().EndsWith(endwith.ToUpper())))
            {
                var interfaceType = item.GetInterfaces().Where(i => i.Name == prefix + item.Name).FirstOrDefault();
                if (interfaceType != null)
                {
                    result.Add(item, interfaceType);
                }
            }
            return result;
        }
    }
}
